package com.love.netty.demo.handler.request;

import com.love.netty.core.packet.request.JoinGroupRequestPacket;
import com.love.netty.core.packet.response.JoinGroupResponsePacket;
import com.love.netty.demo.handler.PacketCodecHandler;
import com.love.netty.util.SessionUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @ClassName: JoinGroupRequestHandler
 * @Description:
 * @Author: wuj
 * @Date: 2021-06-25 15:00
 **/
public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {
    public static final JoinGroupRequestHandler INSTANCE = new JoinGroupRequestHandler();

    private JoinGroupRequestHandler() {

    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, JoinGroupRequestPacket joinGroupRequestPacket) throws Exception {
        // 1. 获取群对应的 channelGroup，然后将当前用户的 channel 添加进去
        String groupId = joinGroupRequestPacket.getGroupId();
        ChannelGroup channelGroup = SessionUtils.getChannelGroup(groupId);
        channelGroup.add(channelHandlerContext.channel());

        // 2. 构造加群响应发送给客户端
        JoinGroupResponsePacket responsePacket = new JoinGroupResponsePacket();

        responsePacket.setSuccess(true);
        responsePacket.setGroupId(groupId);
        channelHandlerContext.channel().writeAndFlush(responsePacket);
    }
}
